package com.gopay.checkorder.service.task;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.util.DateUtils;
import com.gopay.common.util.FtpUtil;
import com.gopay.common.util.SendMail;

/**
 * 民生代扣下载对账文件
 * 
 * @CmbcDownloadOrderTaskImpl.java
 * @author zhengxue
 * @2015-12-22 下午1:47:38 www.gopay.com.cn Inc.All rights reserved.
 */
public class CmbcDownloadOrderTaskImpl implements Task {
    private final static Logger logger = LoggerFactory.getLogger("CHECK_ORDER");
    
    @Resource(name = "cmbcadpayConfig")
    private Map<String, String> cmbcadpayConfig;

    private int port = 21;
    private String samePartnerId = "dk_gfb";
    private String partnerId = "DK_GFB";

    @Override
    public void doTask() {
        logger.error("CmbcDownloadOrderTaskImpl: 定时任务start ");
        try {
            if ("off".equals(cmbcadpayConfig.get("mailSwitch"))) {
                logger.error("CmbcDownloadOrderTaskImpl: 不进行ftp操作直接返回!");
                return;
            }

            String url = cmbcadpayConfig.get("ftp.url");
            String username = cmbcadpayConfig.get("ftp.username");
            String password = cmbcadpayConfig.get("ftp.password");
            String locpath = cmbcadpayConfig.get("ftp.locpath");
            String FTime = DateUtils.getYesterday();
            String FPath = "cmbcadpay";
            String sameFName = samePartnerId + "_DZWJ_" + FTime + ".txt";
            String crossFName = partnerId + "_SSDKDZWJ_" + FTime + ".txt";
            String sfrzFName = partnerId + "_SSSFRZDZWJ_" + FTime + ".txt";
            String encoding = "UTF-8";
            List sendFile = new ArrayList();
            List names = new ArrayList();
            String messageText = "";

            FtpUtil ftpUtil = new FtpUtil();
            // 判断本地服务器是否存在同行代扣对账文件
            if (!(new File(locpath + sameFName).exists())) {
                // 判断本行代扣对账文件是否存在
                if (ftpUtil.exist(url, port, username, password, FPath, sameFName, encoding)) {
                    logger.error("CmbcDownloadOrderTaskImpl " + sameFName + "exist!");
                    // 下载本行代扣对账文件
                    if (FtpUtil.downFile(url, port, username, password, FPath, sameFName, locpath, sameFName, encoding)) {
                        logger.error("CmbcDownloadOrderTaskImpl " + sameFName + " downLoad success!");
                        names.add(sameFName);
                    }
                }
            } else {
                logger.error("CmbcDownloadOrderTaskImpl local " + sameFName + " 对账文件已成功下载, 不再进行ftp操作!");
            }
            
            // 判断本地服务器是否存在跨行代扣对账文件
            if (!(new File(locpath + crossFName).exists())) {
                // 判断跨行代扣对账文件是否存在
                if (ftpUtil.exist(url, port, username, password, FPath, crossFName, encoding)) {
                    logger.error("CmbcDownloadOrderTaskImpl " + crossFName + " exist!");
                    // 下载跨行代扣对账文件
                    if (FtpUtil.downFile(url, port, username, password, FPath, crossFName, locpath, crossFName,
                            encoding)) {
                        logger.error("CmbcDownloadOrderTaskImpl " + crossFName + " downLoad success!");
                        names.add(crossFName);
                    }
                }
            } else {
                logger.error("CmbcDownloadOrderTaskImpl local " + crossFName + " 对账文件已成功下载, 不再进行ftp操作!");
            }
            
            // 判断本地服务器是否存在身份认证对账文件
            if (!(new File(locpath + sfrzFName).exists())) {
                // 判断身份认证对账文件是否存在
                if (ftpUtil.exist(url, port, username, password, FPath, sfrzFName, encoding)) {
                    logger.error("CmbcDownloadOrderTaskImpl " + sfrzFName + " exist!");
                    // 下载身份认证对账文件
                    if (FtpUtil.downFile(url, port, username, password, FPath, sfrzFName, locpath, sfrzFName, encoding)) {
                        logger.error("CmbcDownloadOrderTaskImpl " + sfrzFName + " downLoad success!");
                        names.add(sfrzFName);
                    }
                }
            } else {
                logger.error("CmbcDownloadOrderTaskImpl local " + sfrzFName + " 对账文件已成功下载, 不再进行ftp操作!");
            }
            
            // 若文件以########开头，则代表内容为空
            for (Iterator it = names.iterator(); it.hasNext();) {
                String localPath = locpath + (String) it.next();
                String fileText = readFile(localPath);
                if (fileText.startsWith("########")) {
                    logger.error("CmbcDownloadOrderTaskImpl " + localPath + "is null");
                    it.remove();
                }
            }
            
            // 若对账文件全部为空，则邮件内容标明
            if (names.size() < 1) {
                logger.error("CmbcDownloadOrderTaskImpl: 民生代扣对账文件为null或本地已成功下载!");
                return;
//                messageText = FTime + ": 民生代扣无交易记录!";
            } else {
                messageText = FTime + ": 民生代扣对账文件见附件!" + sameFName + "为: 本行交易记录, " + crossFName + "为: 跨行交易记录"
                        + sfrzFName + "为: 身份认证交易记录";
                for (int i = 0; i < names.size(); i++) {
                    sendFile.add(locpath + (String) names.get(i));
                }
            }
            String subject = "民生代扣对账文件";
            String[] cc = cmbcadpayConfig.get("sendmail.cc").split(","); // 获取多个抄送人
            List ccList = Arrays.asList(cc);

            SendMail.sendMessage(cmbcadpayConfig.get("sendmail.host"), cmbcadpayConfig.get("sendmail.sender"),
                    cmbcadpayConfig.get("sendmail.username"), cmbcadpayConfig.get("sendmail.password"),
                    cmbcadpayConfig.get("sendmail.receiver"), subject, messageText, "text/html;charset=gb2312", ccList,
                    sendFile, names);
        } catch (Exception e) {
            logger.error("CmbcDownloadOrderTaskImpl error: ", e);
        }
    }
    
    /**
     * 获取文件内容
     * 
     * @param path
     * @return
     * @throws IOException
     */
    private String readFile(String path) throws IOException {
        FileReader fr = new FileReader(path);
        BufferedReader br = new BufferedReader(fr);
        StringBuffer sb = new StringBuffer();
        while (br.ready()) {
            sb.append(br.readLine());
        }
        if (null != fr) {
            fr.close();
        }
        if (null != br) {
            br.close();
        }
        return sb.toString();
    }
}
